package com.ml.carManager.utils.map;


import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.auto.ListData;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.ml.carManager.utils.PermissionsUtils;

import java.util.ArrayList;
import java.util.List;

import custom.base.utils.NetStatusUtils;
import custom.base.utils.store.PreferencesManager;

public class LocationUtils implements AMapLocationListener {
    /**
     * 定位工具单例
     */
    private volatile static LocationUtils locationUtil = null;
    /**
     * 定位监听
     */
    private List<OnLocationListener> onLocationListeners = null;
    /**
     * 定位成功自定义实体对象
     */
    public volatile static Location location = null;
    private PreferencesManager<Location> preferencesManager = null;
    private Context context;

    /**
     * 高德定位相关类
     */
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    public LocationUtils(Context context) throws Exception {
        this.context = context;
        locationClient = new AMapLocationClient(this.context);
        locationOption = new AMapLocationClientOption();

        // 设置定位模式为高精度模式
        locationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.Transport);
        // 设置定位监听
        locationClient.setLocationListener(this);

        onLocationListeners = new ArrayList<>();

        preferencesManager = PreferencesManager.getInstance(context);

    }

    /**
     * 得到单例
     */
    public static LocationUtils getInstance(Context context) {
        synchronized (LocationUtils.class) {
            if (locationUtil == null) {
                try {
                    locationUtil = new LocationUtils(context);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            return locationUtil;
        }
    }

    /**
     * 销毁定位
     */
    public void removeLocation(OnLocationListener listener) {
        if (listener != null)
            onLocationListeners.remove(listener);
    }

    /**
     * 销毁定位
     */
    public void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
    }

    /**
     * 销毁定位
     */
    public void destoryLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
            location = null;
            locationUtil = null;
        }
    }

    /**
     * 请求定位,如果未开始定位则会立即开始定位。如果已经定位完成则会立即回调所有注册了监听的位置。
     */
    public void requestLocated(Context context) {


        PermissionsUtils.requestPermission(context, new String[]{Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION}
                , new PermissionsUtils.OnPermissionListener() {
                    @Override
                    public void onRequestSuccess() {
                        location = getHistoryLocation();

                        if (locationClient == null) return;
                        if (new NetStatusUtils(context).isConnected()) {
                            //设置为持续定位
                            locationOption.setOnceLocation(false);

                            // 设置是否需要显示地址信息
                            locationOption.setNeedAddress(true);
                            /**
                             * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
                             * 注意：只有在高精度模式下的单次定位有效，其他方式无效
                             */
                            locationOption.setGpsFirst(false);
                            // 设置发送定位请求的时间间隔,最小值为2000，如果小于2000，按照2000算
                            locationOption.setInterval(Long.valueOf(10 * 1000));
                            // 设置定位参数
                            locationClient.setLocationOption(locationOption);
                            // 启动定位
                            locationClient.startLocation();

                        }
                        if (location != null) {
                            for (OnLocationListener listener : onLocationListeners) {
                                listener.onLocationFinish(location);
                            }
                        }
                    }

                    @Override
                    public void onRequestFail() {

                    }
                });
    }

    @SuppressWarnings("static-access")
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation == null || (aMapLocation != null && aMapLocation.getErrorCode() != 0)) {
            return;
        }
        String desc = "";
        Bundle locBundle = aMapLocation.getExtras();
        if (locBundle != null) {
            desc = locBundle.getString("desc");
        }
        Location l = new Location();
        l.setCity(aMapLocation.getCity());
        l.setProvince(aMapLocation.getProvince());
        l.setShortAddress(AMapUtil.getShortAddress(desc, aMapLocation).trim());
        l.setLat(aMapLocation.getLatitude());
        l.setLng(aMapLocation.getLongitude());
        l.setSlat(aMapLocation.getLatitude() + "");
        l.setSlng(aMapLocation.getLongitude() + "");
        l.setCountry(aMapLocation.getCountry());
        l.setDesc(desc);
        l.setCityCode(aMapLocation.getCityCode());

        this.location = l;
        if (preferencesManager != null) {
            preferencesManager.putObject(PreferencesManager.PRE_HISTORY_LOCATION, location);
        }

        if (onLocationListeners.size() > 0) {
            for (OnLocationListener listener : onLocationListeners) {
                listener.onLocationFinish(location);
            }
        }
    }

    public void addLocationListener(OnLocationListener onLocationListener) {
        if (!onLocationListeners.contains(onLocationListener))//如果已包含则不添加
            onLocationListeners.add(onLocationListener);
        if (location != null) {
            for (OnLocationListener listener : onLocationListeners) {
                listener.onLocationFinish(location);
            }
        }
    }

    /**
     * 得到历史位置对象
     */
    private Location getHistoryLocation() {
        if (preferencesManager == null) return null;
        return preferencesManager.getObject(PreferencesManager.PRE_HISTORY_LOCATION, Location.class);
    }

    /**
     * 定位是否成功过
     */
    public boolean isLocationSuccessed() {
        return location != null;
    }

    /**
     * 定位回调接口
     */
    public interface OnLocationListener {
        void onLocationFinish(Location location);
    }

    public static Location getLocation() {
        return location;
    }
}